package cn.jiyun.security;

import cn.jiyun.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class SpringSecurityUserService implements UserDetailsService {

/*    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;*/

    //模拟向数据库中插入数据
    public Map<String, UserInfo> map = new HashMap<String, UserInfo>();

    public void init(){
//        bCryptPasswordEncoder.encode("1234")
        map.put("admin",new UserInfo("admin","1234"));
        map.put("test",new UserInfo("test","1234"));
    }


    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        init();
        //模拟从数据库中查询用户
        UserInfo userInfo = map.get(username);
        if(userInfo==null){
            return null;
        }

        //模拟查询数据库中用户的密码
        String password = "{noop}"+userInfo.getPassword();
        List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
        //授权，后期需要改为查询数据库动态获得用户拥有的权限和角色
        if("admin".equals(username)){
            list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        }

        if("test".equals(username)){
            list.add(new SimpleGrantedAuthority("ROLE_TEST"));
        }

        return new org.springframework.security.core.userdetails.User(username, password, list);
    }
}
